<template>
    <div class="container">
        <a-form ref="searchForm" :model="search" autocomplete="off" @keyup.enter="handleSearch()">
            <iSearch>
                <template #FormData>
                    <a-form-item>
                        <iInput v-model:value="search.account" tip="会员账号（邮箱）" placeholder="请输入会员账号（邮箱）"></iInput>
                    </a-form-item>
                    <a-form-item>
                        <iSelect v-model:value="search.group_id" :option="MemberGroup" index="id" label="group_name" tip="会员分组"></iSelect>
                    </a-form-item>
                    <a-form-item>
                        <a-checkbox-group v-model:value="search.state">
                            <a-checkbox v-for="(item,index) in DbMemberState" :key="index" :value="item.value">{{ item.label }}</a-checkbox>
                        </a-checkbox-group>
                    </a-form-item>
                    <a-form-item>
                        <iDateRangePick v-model:value="search.regis_time" tip="注册时间" @change="handleStart" placeholder="注册时间" />
                    </a-form-item>
                </template>
                <template #Button>
                    <a-button type="primary" @click="handleSearch">查询</a-button>
                    <a-button @click="handleReset">重置</a-button>
                    <a-button type="primary" danger v-iscan="['member:add']" @click="handleAdd">添加</a-button>
                </template>
            </iSearch>
        </a-form>
        <iTable @search="handlePagination" :total="total" :columns="columns" :tableData="tableData" :loading="loading">
            <template #account="{ record }">
                <div>
                    钱包：<span style="text-decoration: underline;font-weight: 600;margin-right: 10px;">{{ Number(record.wallet).toFixed(2) }}</span>
                    <a href="javascript:void(0)" v-iscan="['member:adjust_wallet']" @click="handleAdjustWallet(record)">调整金额</a>
                </div>
                <div>
                    <span style="text-decoration: underline;font-weight: bold;">{{ record.account }}</span>
                    <span style="cursor: pointer;margin-left: 5px" @click="handleCopyAccount(record.account)">
                        <CopyTwoTone />
                    </span>
                </div>
            </template>
            <template #state="{ record }">
                <a-tag style="margin: 0 auto" :color="FuncDbMemberState(record.state || 0).color">{{ FuncDbMemberState(record.state || 0).label }}</a-tag>
            </template>
            <template #regis_info="{ record }">
                <div>{{ record.regis_ip || '--' }}</div>
                <div>{{ record.regis_time ? $Date(record.regis_time) : '--' }}</div>
            </template>
            <template #operate="{ record }">
                <a-flex gap="small" horizontal>
                    <a-button type="link" v-iscan="['member:edit']" @click="handleEdit(record.id)">编辑</a-button>
                </a-flex>
            </template>
        </iTable>
        
        <a-drawer :title="(formState.id || 0) > 0 ? '编辑会员': '添加会员'" rootClassName="full-modal-drawer" width="40%" :open="EditVisible" @close="handleEditClose()" :loading="EditLoading">
            <a-form ref="formStateRef" :model="formState" autocomplete="off" :rules="formStateRule" layout="vertical">
                <a-form-item name="group_id" label="分组">
                    <a-select v-model:value="formState.group_id">
                        <a-select-option v-for="item in MemberGroup" :value="item.id">{{ item.group_name }}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item name="account" label="会员账号（邮箱）">
                    <a-input v-model:value="formState.account" :disabled="(formState.id || 0) > 0" placeholder="请输入会员账号（邮箱）"></a-input>
                </a-form-item>
                <a-form-item name="password" label="密码">
                    <a-input v-model:value="formState.password" placeholder="请输入密码"></a-input>
                </a-form-item>
                <a-form-item name="state" label="状态">
                    <a-radio-group v-model:value="formState.state" name="state">
                        <a-radio v-for="(item,index) in DbMemberState" :key="index" :value="item.value">{{ item.label }}</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-form>
            <template #extra>
                <a-space>
                    <a-button @click="handleEditClose()">取消</a-button>
                    <a-button type="primary" @click="handleSubmit()">保存</a-button>
                </a-space>
            </template>
        </a-drawer>

        <WalletTransaction :member_id="EditMemberId" :visible="AdjustWalletVisible" @close="AdjustWalletVisible = false" />
        
    </div>
</template>


<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { iPb } from '@/protobuf/interface/index'
import { ListMember, ReadMember, CreateMember, UpdateMember } from '@/api/member';
import { ListMemberGroup } from '@/api/member_group';
import { DbMemberState, FuncDbMemberState } from '@/tool/const'
import { FormInstance } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { Message } from '@/tool/antdv';
import { $Date } from '@/tool/function';
import { TableWidth } from '@/tool/enum';
import WalletTransaction from "./wallet_transaction/index.vue"
import { Dayjs } from 'dayjs';
import { TimeDay } from '@/tool/time';
import useClipboard from 'vue-clipboard3'
const { toClipboard } = useClipboard()


const formStateRef = ref<FormInstance>()
const formState = ref<iPb.IDbMember>(iPb.DbMember.create())
const formStateRule = reactive({
    group_id: [
        { required: true, message: '请选择会员分组' }
    ],
    account: [
        { required: true, message: '请输入会员账号' },
        { pattern: /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/ ,message: '郵箱格式不正確', trigger: 'change' }
    ],
    password: [
        { required: true, message: '请输入登入密码', whitespace: true }
    ]
})
const search = ref<iPb.Admin.IListMemberRequest>(iPb.Admin.ListMemberRequest.create({
        regis_time: TimeDay()
}))
const loading = ref<boolean>(false)
const EditVisible = ref<boolean>(false)
const EditLoading = ref<boolean>(false)

const tableData = ref<Array<iPb.IDbMember>>([])
const total = ref<number>(0)
const MemberGroup = ref<Array<iPb.IDbMemberGroup>>([])

const handleCopyAccount = (account: string) => {
    toClipboard(account)
    Message.success({
        content: "拷贝成功",
    })
}

const handleAdd = () => {
    formStateRule.password = [
        { required: true, message: '请输入登入密码', whitespace: true }
    ]
    formStateRef.value?.resetFields()
    formState.value = iPb.DbMember.create()
    formState.value.group_id = MemberGroup.value[0].id
    EditVisible.value = true
}
const handleEditClose = () => {
    EditVisible.value = false
}

const AdjustWalletVisible = ref<boolean>(false)
const EditMemberId = ref<number>(0)

const handleAdjustWallet = (record: iPb.DbMember) => {
    EditMemberId.value = record.id
    AdjustWalletVisible.value = true
}

const handleEdit = (id: number) => {
    formStateRule.password = []
    formStateRef.value?.resetFields()
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    const ReadMemberRequest = iPb.Admin.ReadMemberRequest.create({
        id: id
    })
    ReadMember(ReadMemberRequest).then((result:iPb.IDbMember) => {
        formState.value = iPb.DbMember.create(result)
        EditVisible.value = true
        EditLoading.value = false
    }).catch(() => {
        EditLoading.value = false
    })
}

const handleSubmit = () => {
    const formData = formState.value
    formStateRef.value?.validate().then(() => {
        if(EditLoading.value) {
            return
        }
        EditLoading.value = true
        if((formData.id || 0) > 0) {
            UpdateMember(formData).then((_result:iPb.Admin.IUpdateMemberResponse) => {
                EditLoading.value = false
                EditVisible.value = false
                Message.success({
                    content: "保存成功",
                })
                initList()
            }).catch(() => {
                EditLoading.value = false
            })
        }else {
            CreateMember(formData).then((_result:iPb.Admin.ICreateMemberResponse) => {
                EditLoading.value = false
                EditVisible.value = false
                Message.success({
                    content: "添加成功",
                })
                initList()
            }).catch(() => {
                EditLoading.value = false
            })
        }
    })
}

const handleReset = () => {
    search.value = iPb.Admin.ListMemberRequest.create({
        regis_time: TimeDay()
    })
    search.value.group_id = 0
    initList()
}

const handleSearch = () => {
    initList()
}

const handleStart = (e: Dayjs[]) => {
    search.value.regis_time = e
}

const handlePagination = (e: { current: number | undefined; pageSize: number | undefined; }) => {
    initList(e.current, e.pageSize)
}

const initList = (page = 1, limit = 15) => {
    if(loading.value) {
        return
    }
    loading.value = true
    search.value.limit = limit
    search.value.page = page
    ListMember(iPb.Admin.ListMemberRequest.create(search.value)).then((result:iPb.Admin.IListMemberResponse) => {
        let R = iPb.Admin.ListMemberResponse.create(result)
        tableData.value = R.data
        total.value = R.count
        loading.value = false
    })
}

const initListMemberGroup = () => {
    ListMemberGroup(iPb.Admin.ListMemberGroupRequest.create()).then((result:iPb.Admin.IListMemberGroupResponse) => {
        let R = iPb.Admin.ListMemberGroupResponse.create(result)

        MemberGroup.value = R.data
    })
}

const columns:TableColumnsType = [
    {
        title: "ID",
        dataIndex: "id",
        width: TableWidth.Id,
    },
    {
        title: "会员分组",
        dataIndex: "group_name",
        width: TableWidth.Group,
    },
    {
        title: "会员账号（邮箱）",
        dataIndex: "account",
        width: TableWidth.Info,
    },
    {
        title: "状态",
        dataIndex: "state",
        width: TableWidth.State,
        align: "center"
    },
    {
        title: "最后登入时间",
        dataIndex: "last_login_time",
        key: "time",
        width: TableWidth.Time,
    },
    {
        title: "注册信息",
        dataIndex: "regis_info",
        width: TableWidth.Time,
    },
    {
        title: "操作",
        dataIndex: "operate",
        width: TableWidth.Operate,
    }
]

onMounted(() => {
    initList()
    initListMemberGroup()
})

</script>


<style lang="less">
.third-layer {
    .ant-tree-list-holder-inner {
        display: inline-block !important;
    }
}
.last-layer {
    display: inline-flex !important;
}
</style>
